package org.koyad.portal.actions;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.koyad.portal.annotations.Action;
import org.koyad.portal.annotations.Action.Forward;
import org.koyad.portal.api.BaseAction;
import org.koyad.portal.constants.FrameworkConstants;
import org.koyad.portal.context.PistonContext;
import org.koyad.portal.exceptions.FrameworkException;
import org.koyad.portal.exceptions.ValidationErrorCodes;
import org.koyad.portal.utils.LogUtils;

@Action(
	name = "login",
	forwards = { 
					@Forward(name = "success", path = "/jsp/success.jsp"),
					@Forward(name = "failure", path = "/jsp/failure.jsp")
			   }
)
public class LoginAction extends BaseAction {

	private static final LogUtils LOGGER = LogUtils.getLogger(LoginAction.class);
	
	@Override
	public void execute() {
		HttpServletRequest req = PistonContext.getContext().getRequest();
		String uname = req.getParameter("uname");
		String pwd = req.getParameter("pwd");
		try {
			//login
			req.login(uname, pwd);
			
			//invalidate view tree
//			PistonContext.getContext().resetViewRoot();
			
			//redirect to original page
			HttpServletResponse resp = PistonContext.getContext().getResponse();
			try {
				Cookie[] cookies = req.getCookies();
				for(Cookie cookie : cookies) {
					if(cookie.getName().equals(FrameworkConstants.PISTON_REDIRECT_URL)) {
						cookie.setMaxAge(0);
						resp.addCookie(cookie);
						LOGGER.info("REDIRECT URL : " + cookie.getValue());
						resp.sendRedirect(cookie.getValue());
						break;
					}
				}
			} catch (IOException e) {
				LOGGER.logException(e);
				throw new FrameworkException("");
			}
		} catch (ServletException e) {
			LOGGER.logException(e);
			PistonContext.getContext().getViewRoot().addError(ValidationErrorCodes.FWKLGN001);
		}
	}

}
